package com.example.tutorial.java.concurrent.thread.lock;

/**
 * @description:
 * @author: cph
 * @date: 2022-2-15
 */
public class AutomicDemo {

    int i = 0;

    public synchronized void incr() {
        i++;
    }

    public static void main(String[] args) {
        AutomicDemo demo = new AutomicDemo();
        Thread[] threads = new Thread[2];
        for (int j = 0; j < threads.length; j++) {
            threads[j] = new Thread(() -> {
                for (int k = 0; k < 10000; k++) {
                    demo.incr();
                }
            });
            threads[j].start();
        }

        try {
            threads[0].join();
            threads[1].join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 预期20000，实际多数情况下小于20000
        System.out.println(demo.i);

    }
}
